<template>
  <div class="page">

    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="角色名称：">
          <el-input v-model="formInline.roleName" placeholder="角色名称"></el-input>
        </el-form-item>

      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="getList">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <el-button type="primary" size="small" @click="openDialog()">新增角色</el-button>
      </div>
      <!-- 操作区域 end -->
      <el-table class="el_table" size="small" :data="tableData">
        <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip />
        <el-table-column prop="createdDate" label="创建时间" />
        <el-table-column prop="createdDate" label="操作" width="200px">
          <template slot-scope="scope">
            <el-link type="primary" class="el_link" @click="openDialog(scope.row.id)">编辑</el-link>
            <el-link type="danger" class="el_link" @click="remove(scope.row.id)">删除</el-link>
            <!-- <el-button type="primary" plain size="mini" :id="scope.row.id" @click="openDialog(scope.row.id)">编辑</el-button> -->
            <!-- <el-button type="danger" plain size="mini" @click="remove(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize" :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList" @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->
    <public-dialog :show="showDialog" :title="currentId ? '编辑角色' : '新增角色'" @close="closeDialog">
      <div>
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="120px" size="small">
          <el-form-item label="角色名称：" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <!-- <el-form-item label="备注：">
              <el-input type="textarea" v-model="addForm.remark"></el-input>
            </el-form-item> -->
          <el-form-item label="功能权限：" prop="menuIdList">
            <div class="roles_box">
              <el-tree ref="addTree" :check-strictly="true" :props="treeProps" :data="treeData" :default-checked-keys="addForm.menuIdList" default-expand-all highlight-current show-checkbox node-key="id" @check="onCheck">
              </el-tree>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" plain size="small" @click="saveInfo">确定</el-button>
        <el-button type="default" plain size="small" @click="closeDialog">取消</el-button>
      </div>
    </public-dialog>
</div>
</template>

<script>
import {
  GETROLESEARCH,
  GETMENUCHECKEDTREE,
  ADDROLE,
  GETROLEINFO,
  EDITROLEINFO,
  DELETEROLE,
} from "@/http/system";
import { showModal, showToast, deepClone } from "@/common/util";
import PublicDialog from "@/components/Dialog";

export default {
  components: {
    PublicDialog,
  },
  data() {
    var checkMenu = (rule, value, callBack) => {
      if (value && value.length == 0) {
        return callBack(new Error("请选择菜单列表"));
      } else {
        return callBack();
      }
    };
    return {
      formInline: {},
      tableData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 30, 40],
      pageSize: 10,
      loading: false,
      showDialog: false,
      currentId: "",
      addForm: { menuIdList: [], enableStatus: 1 },
      vList: [],
      typeList: [
        { code: 0, value: "本人" },
        { code: 1, value: "本人及下属" },
        { code: 2, value: "本部门" },
        { code: 3, value: "本部门及下级部门" },
        { code: 4, value: "全部" },
      ],
      treeProps: {
        children: "children",
        label: "label",
      },
      treeData: [],
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        enableStatus: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        roleVisibility: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        rolePermissionType: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        menuIdList: [
          {
            required: true,
            validator: checkMenu,
            message: "请选择",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 获取列表 */
    getList() {
      let _this = this;
      let oParams = _this.getParams();
      oParams.pageNumber = _this.pageNumber;
      _this.loading = true;
      GETROLESEARCH(oParams).then((res) => {
        _this.loading = false;
        let obj = res.data || {};
        _this.tableData = obj.list || [];
        _this.pageTotal = obj.totalElements;
      });
    },
    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e;
      this.getList();
    },

    /** 获取参数 */
    getParams() {
      let o = JSON.parse(JSON.stringify(this.formInline));
      o.pageSize = this.pageSize;
      return o;
    },

    /** 删除角色 */
    remove(id) {
      let _this = this;
      showModal({
        message: "确认删除该角色吗？",
        success: () => {
          DELETEROLE({ id: id }).then((res) => {
            if (res.code == 200) {
              showToast({
                message: "删除成功",
              });
              _this.getList();
            }
          });
        },
      });
    },

    /** 打开弹框 */
    openDialog(id) {
      this.currentId = id;
      this.showDialog = true;
      if (id) {
        this.getRoleInfo(id);
      }
      this.getMenuTree(id);
    },

    /** 关闭弹框 */
    closeDialog() {
      this.currentId = "";
      this.showDialog = false;
      this.addForm = {};
    },

    /** 获取树 */
    getMenuTree(id) {
      let _this = this;
      GETMENUCHECKEDTREE({ roleId: id }).then((res) => {
        let obj = res.data || {};
        _this.treeData = obj.menuTree || [];
        _this.addForm.menuIdList = obj.checkedIds || [];
      });
    },

    /** 保存数据 */
    saveInfo() {
      let that = this;
      that.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        let oParams = JSON.parse(JSON.stringify(that.addForm));
        oParams.menuIdList = this.$refs.addTree.getCheckedKeys();
        oParams.halfSelectedMenuIdList = this.$refs.addTree.getHalfCheckedKeys()
        that.loading = true;
        if (that.currentId) {
          EDITROLEINFO(oParams).then((res) => {
            that.loading = false;
            if (res.code == 200) {
              that.closeDialog();
              that.getList();
              showToast({
                message: "编辑成功",
                type: "success",
              });
            }
          });
          return false;
        }
        ADDROLE(oParams).then((res) => {
          that.loading = false;
          if (res.code == 200) {
            that.closeDialog();
            that.getList();
            showToast({
              message: "添加成功",
              type: "success",
            });
          }
        });
      });
    },

    /** 监听树勾选 */
    onCheck(node, data) {
      let checked = data.checkedKeys.findIndex(k => k == node.id) >= 0
      this.$set(this.addForm, 'menuIdList', data.checkedKeys)
      let child = this.flattenDeep(node.children);
      // 勾选操作
      if (checked) {
        this.getCheckedIds(child)
      } else {
        this.removeCheckedIds(child)
      }
      this.$refs.addForm.validateField("menuIdList");
    },

    // 全选子级
    getCheckedIds(list) {
      let _this = this;
      let arr = this.addForm.menuIdList || []
      list.map(k => {
        arr.push(k.id)
      })
      this.$set(_this.addForm, 'menuIdList', arr)
      _this.$refs.addTree.setCheckedKeys(arr)
    },

    // 删除子级
    removeCheckedIds(list) {
      let arr = []
      let checkedList = this.addForm.menuIdList || []
      arr = checkedList.filter(k => {
        let idx = list.findIndex(j => j.id == k);
        return idx < 0
      })
      this.$set(this.addForm, 'menuIdList', arr)
      this.$refs.addTree.setCheckedKeys(arr)
    },

    // 展开子节点
    flattenDeep(arr) {
      let res = [];
      for (let i = 0; i < arr.length; i++) {
        let obj = arr[i]
        if (obj.children && obj.children.length) {
          res = res.concat(this.flattenDeep(obj.children));
          //删除父级的children属性，须保留children则把这行删除
          //delete obj.children
        }
        res.push(obj);
      }
      return res;
    },

    // 获取树选中
    getTreeNodes() {
      let m = this.$refs.addTree.getCheckedNodes(false, true)
      let arr = [];
      m.map(k => {
        arr.push(k.id)
      })
      return arr;
    },

    /** 获取角色信息 */
    getRoleInfo(id) {
      let that = this;
      GETROLEINFO({ id: id }).then((res) => {
        let obj = res.data || {};
        delete obj.createdDate;
        delete obj.maxUser;
        if (obj.roleTenants == null) {
          delete obj.roleTenants;
        }
        obj.roleId = obj.id;
        delete obj.id;
        that.addForm = obj;
      });
    },

    /** 重置 */
    rest() {
      this.formInline = {};
      this.orderTime = [];
      this.getList();
    },
  },
  computed: {},
};
</script>

<style lang="scss" scoped>
.stop_status,
.normal_status {
  position: relative;
  padding-left: 10px;
  color: #f00;
}

.normal_status {
  color: #31b311;
}

.stop_status:after,
.normal_status:after {
  display: block;
  content: "";
  width: 8px;
  height: 8px;
  border-radius: 100%;
  background: #f00;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translate(0, -50%);
}

.normal_status:after {
  background: #31b311;
}
.roles_box{
  max-height: 300px;
  overflow-y: auto;
}
</style>
